<template>
  <div class="ring_main">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="全部" name="first" code="" style="font-size: 18px!important;"></el-tab-pane>
      <el-tab-pane label="电信" name="second" code="01"></el-tab-pane>
      <el-tab-pane label="联通" name="fourth" code="02"></el-tab-pane>
      <el-tab-pane label="移动" name="third" code="03"></el-tab-pane>
    </el-tabs>

    <el-container class="ring_container">
      <el-aside width="300px" class="ring_left_menu">
        <div style="font-size: 14px;font-weight: bolder; height: 30px;margin-bottom: 20px;">套餐类型
          <i class="el-icon-plus" v-if="userInfo.isSuperAdmin==='1'" style="float: right;color: #5B73FF;" @click="addPackage"></i>
        </div>
        <div>
          <div v-for="(i,x) in packageList" :ref="`package${x}`" :key="x" @mouseover="mouseover(i)"
               @click="packageClick(i,x)"
               @mouseleave="mouseleave(i)" style="line-height: 30px;color: #646C9A;font-size: 14px;cursor:pointer">
            <span v-show="!i.eidt">{{ i.packageName }}</span>
            <el-input v-model="i.packageName" :ref="`input${x}`" v-show="i.eidt" size="small" placeholder="请输入套餐名"
                      @blur="saveName(i)" maxlength="10"
                      show-word-limit></el-input>
            <template v-if="!!i.showEdit && i.showEdit">
                 <span v-show="!i.eidt" style="float: right;">
                  <i class="el-icon-edit" style="color: #5B73FF;" @click="clickEdit(i,x)"></i>
                  <i class="el-icon-delete" style="color: #ff3300;" @click="deletePackage(i)"></i>
                </span>
            </template>
          </div>
        </div>
      </el-aside>
      <el-main style="background: #fff;position: relative;">
        <div v-show="currentPackage.id">
          <div style="text-align: left">{{ currentPackage.packageName }}</div>
          <div class="template-form">
            <el-form :model="currentPackage" :rules="rules" ref="currentPackage" label-width="100px"
                     class="template-form__list" style="align-items: center;">
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="运营商：" prop="operator">
                    <el-select v-model="currentPackage.operator"
                               :disabled="!!currentOperator || !editAble"
                               placeholder="请选择运营商" style="width: 300px;">
                      <el-option v-for="{code,name} in operatorCode" :label="name" :value="code"
                                 :key="code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="套餐价格：" prop="packagePrice">
                    <el-input :readonly="!editAble" v-model="currentPackage.packagePrice"
                              style="width: 300px;"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="佣金金额：" prop="commission">
                    <el-input :readonly="!editAble" v-model="currentPackage.commission"
                              style="width: 300px;"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="套餐说明：" prop="packageExplain">
                    <el-input :readonly="!editAble" type="textarea" :rows="13" v-model="currentPackage.packageExplain"
                              style="width: 400px;" maxlength="500"
                              show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="userInfo.isSuperAdmin==='1'">
              <el-button v-show="!editAble" type="primary" @click="editAble=true">编辑</el-button>
              <el-button v-show="editAble" type="danger" @click="cancel">取消</el-button>
              <el-button v-show="editAble" type="primary" @click="savePackage">保存</el-button>
            </div>
          </div>
        </div>

      </el-main>

    </el-container>

  </div>

</template>

<script>
import request from "@/utils/Request";
import {operatorCode, getOperatorName} from "@/common/PublicCode"

export default {
  name: "MaintenanceManager",
  data() {
    const validatePackagePrice = (rule, value, callback) => {
      if ((parseFloat(value).toString() === "NaN")) {
        callback(new Error('请输入正确的套餐价格'));
      } else {
        callback();
      }
    };
    const validateCommission = (rule, value, callback) => {
      if ((parseFloat(value).toString() === "NaN")) {
        callback(new Error('请输入正确的佣金金额'));
      } else {
        callback();
      }
    };
    return {
      getOperatorName: getOperatorName,
      editAble: false,
      operatorCode: operatorCode,
      activeName: 'first',
      packageList: [],
      currentPackage: {},
      oriPackage: {},
      currentOperator: '',
      rules: {
        packagePrice: [
          {required: true, message: '请输入套餐价格', trigger: 'blur'},
          {min: 1, max: 10, message: '长度在 1 到 8 个字符', trigger: 'blur'},
          {validator: validatePackagePrice, trigger: 'blur'}
        ],
        commission: [
          {required: true, message: '请输入佣金金额', trigger: 'blur'},
          {min: 1, max: 6, message: '长度在 1 到 8 个字符', trigger: 'blur'},
          {validator: validateCommission, trigger: 'blur'}
        ],
        operator: [
          {required: true, message: '请选择运营商', trigger: 'change'}
        ],
        packageExplain: [
          {required: true, message: '请填写套餐说明', trigger: 'blur'}
        ]
      }
    };
  },
  mounted() {
    this.init();
  },
  activated() {
    this.showChoicesPackage();
  },
  methods: {
    packageClick(i, x) {
      this.editAble = false;
      this.currentPackage = JSON.parse(JSON.stringify(i));
      this.oriPackage = JSON.parse(JSON.stringify(this.currentPackage));
      this.packageList.forEach((p, x) => {
        this.$refs[`package${x}`][0].style.color = '';
        this.$refs[`package${x}`][0].style['background-color'] = '';
      })
      this.$refs[`package${x}`][0].style.color = 'blue';
      this.$refs[`package${x}`][0].style['background-color'] = 'rgb(239, 242, 255)';
    },
    cancel() {
      this.currentPackage = JSON.parse(JSON.stringify(this.oriPackage));
      this.editAble = false;
    },
    mouseover(i) {
      this.$set(i, 'showEdit', true);
    },
    mouseleave(i) {
      this.$set(i, 'showEdit', false);
    },
    showChoicesPackage() {
      if (!!this.$route.query.packageId && this.packageList.length > 0) {
        this.$nextTick(() => {
          const packageIndex = this.packageList.findIndex(p => p.id === this.$route.query.packageId);
          this.packageClick(this.packageList[packageIndex], packageIndex)
        })
      }
    },
    clickEdit(i, x) {
      i.eidt = true;
      this.$nextTick(() => {
        this.$refs[`input${x}`][0].focus();
      })
    },
    init() {
      request.get('/telecomPackage/getList', {params: {"operator": this.currentOperator}}).then(({data}) => {
        if (data.success) {
          data.data.forEach(i => {
            i.eidt = false
          });
          this.packageList = JSON.parse(JSON.stringify(data.data));
          if (this.packageList.length > 0) {
            this.$nextTick(() => {
              this.packageClick(this.packageList[0], 0);
            })
          } else {
            this.currentPackage = {};
          }
          this.showChoicesPackage();
        }
      }).catch(err => {
        this.$message({type: 'error', message: "查询套餐列表失败"});
        console.log(err)
      })
    },
    async deletePackage(data) {
      const confirm = await this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return true;
      }).catch(() => {
        return false;
      });
      if (!confirm) {
        return;
      }
      request.post('/telecomPackage/deletePackage', data).then(({data}) => {
        if (data.success) {
          this.init();
          this.$message({type: 'success', message: "删除套餐成功"});
        } else {
          this.$message({type: 'warning', message: data.message});
        }
      }).catch(err => {
        this.$message({type: 'error', message: err.message});
        console.log(err)
      })
    },
    saveName(_package) {
      if (!_package.packageName) {
        _package.packageName = '未命名套餐'
      }
      _package.eidt = false;
      request.post('/telecomPackage/saveName', _package).then(({data}) => {
        if (data.success) {
          this.currentPackage = data.data;
          _package.id = data.data.id;
          this.editAble = true;
          // this.$message({type: 'success', message: "套餐名称已修改"});
        } else {
          throw new Error(data.message);
        }
      }).catch(err => {
        this.$message({type: 'error', message: err.message});
        console.log(err)
      })
    },
    async savePackage() {
      const validate = await new Promise((resolve, reject) => {
        this.$refs.currentPackage.validate(v => {
          resolve(v);
        })
      })
      if (validate) {
        const confirm = await this.$confirm('是否确认保存?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return true;
        }).catch(() => {
          return false;
        });
        if (!confirm) {
          return;
        }
        this.editAble = false;
        let {packagePrice, commission} = this.currentPackage;
        this.currentPackage.packagePrice = parseFloat(packagePrice).toString();
        this.currentPackage.commission = parseFloat(commission).toString();
        request.post('/telecomPackage/savePackage', this.currentPackage).then(({data}) => {
          if (data.success) {
            this.$message({type: 'success', message: "保存套餐成功"});
            this.init();
          } else {
            throw new Error(data.message);
          }
        }).catch(err => {
          this.$message({type: 'error', message: "保存套餐失败"});
          console.log(err)
        })
      }
    },
    addPackage() {
      this.packageList.unshift({packageName: '', operator: this.currentOperator, eidt: true});
      this.$nextTick(() => {
        this.$refs.input0[0].focus()
      })

    },
    handleClick(tab, event) {
      this.currentOperator = tab.$attrs.code;
      this.init();
    },
  },
  computed: {
    userInfo() {
      return JSON.parse(localStorage.getItem('userInfo'));
    }
  },
}
</script>

<style scoped>
.el-header, .el-footer {
  background-color: #B3C0D1;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
}

body > .el-container {
  margin-bottom: 40px;
}

.ring_main {
  background: #f1f2f7;
}

.ring_container {
  background: #ffffff;
  /* padding: 20px;*/
  border-radius: 3px;
  width: 100%;
  height: 600px;
}

.ring_container > .ring_left_menu {
  /* width:200px;*/
  background: none;
  border-right: 1px solid #f2f2f2;
  padding: 20px;

}

.ring_left_menu .el-icon-edit, .ring_left_menu .el-icon-delete {
  margin-left: 10px;
}

.dialog-footer {
  height: 70px;
  align-items: center;
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 0;
  width: calc(100% - 40px);
  background: #fff;
}

</style>